﻿#include"stdafx.h"
#include"SQLexpression.h"

bool SqlEx::ForSelect() {

	string db = CStringTostring(pSocket->cur_db);
	if (db == "") {
		pSocket->SendMSG("Please choose a database !");
		return 0;
	}
	
	string msg = "";
	vector<insert_model>fields;
	vector<struct_where>wh;
	string tname;
	regex reg1("(?<=select).+?(?=from)");
	regex reg2("((?<=from ).+?(?= where))|((?<=from ).+?(?=END))");
	regex reg3("(?<=where ).+?(?=END)");
	smatch sm;

	if (regex_search(Ex, sm, reg1)) {
		string ss = sm.str();
		ss = trimAll(ss, " ");
		vector<string>temp = split(ss, ",");
		for (unsigned int i = 0; i < temp.size(); i++) {
			insert_model m;
			m.key = temp[i];
			fields.push_back(m);
		}
	}
	else {
		msg = "检查select 和from语句之间是否存在错误！！！";
		pSocket->SendMSG(msg);
		return false;
	}
	if (regex_search(Ex, sm, reg2)) {
		string ss = sm.str();
		tname = trimAll(ss, " ");
	}
	else {
		msg = "检查from语句后是否存在错误！！！";
		pSocket->SendMSG(msg);
		return false;
	}
	if (!authority->Auth_Judge(user_host, db, tname)) {
		pSocket->SendMSG("You do not have permission to query the table !");
		return 0;
	}
	if (regex_search(Ex, sm, reg3)) {
		string test = sm.str();
		test = trimAll(test, " ");
	    where(test,wh);
	}
	serverDB->Table_Select(tname.c_str(),CStringTostring(pSocket->cur_db), fields, wh, msg);
	if (msg == ""||msg=="\r\n")
		msg = "Null set !";
	pSocket->SendMSG(msg);
	return true;
}